package look4ss.aplicativo;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.sdsmdg.tastytoast.TastyToast;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import de.hdodenhof.circleimageview.CircleImageView;

public class ActivityRegistro2 extends AppCompatActivity {
    private CircleImageView imagemPersonalizar;
    private Button botaoFinalizar;
    private SharedPreferences sharp;
    private Uri imagemUrl = null;
    private EditText definirNome;
    private ProgressDialog carregandoTela;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_registro2);

        carregandoTela = new ProgressDialog(this);
        imagemPersonalizar = findViewById(R.id.imagemConfig);
        botaoFinalizar = findViewById(R.id.botaoConcluir);
        definirNome = findViewById(R.id.definirNome);

        botaoFinalizar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                personalizarConta();

            }
        });

        imagemPersonalizar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                startActivityForResult(intent, 1);
            }
        });
    }

    private void personalizarConta() {
        String nome = definirNome.getText().toString();
        carregandoTela.setMessage(getString(R.string.finalizando_registro));
        carregandoTela.show();

        if (nome.isEmpty()) {
            TastyToast.makeText(ActivityRegistro2.this, getString(R.string.digite_nome), Toast.LENGTH_LONG, TastyToast.WARNING);
            carregandoTela.dismiss();
            return;
        }else{
            sharp = getSharedPreferences("usuario", Context.MODE_PRIVATE);
            SharedPreferences.Editor edtr = sharp.edit();
            edtr.putString("nome", nome);
            edtr.apply();

            carregandoTela.dismiss();
        }


            try {
            String idUsuario_imagem = FirebaseAuth.getInstance().getCurrentUser().getUid();
            StorageReference sr = FirebaseStorage.getInstance().getReference().child("imagens_perfil/" + idUsuario_imagem + ".jpg");
            sr.putFile(imagemUrl).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                    carregandoTela.dismiss();
                    startActivity(new Intent(ActivityRegistro2.this, ActivityLogin.class));
                    finish();
                }
            });
        } catch (Exception e) {
        }
        if (imagemUrl == null) {
            TastyToast.makeText(ActivityRegistro2.this, getString(R.string.escolha_foto_perfil), Toast.LENGTH_LONG, TastyToast.WARNING);
            return;
        }
    }

    @Override
    protected void onActivityResult(int codigoRequisicao, int codigoResultado, Intent data) {
        try {
            super.onActivityResult(codigoRequisicao, codigoResultado, data);
            Uri UriImagem = data.getData();
            if (codigoRequisicao == 1 && codigoResultado == RESULT_OK && UriImagem != null) {
                CropImage.activity(UriImagem)
                        .setGuidelines(CropImageView.Guidelines.ON)
                        .start(this);
            }
            if (codigoRequisicao == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
                CropImage.ActivityResult result = CropImage.getActivityResult(data);
                if (codigoResultado == RESULT_OK) {
                    imagemUrl = result.getUri();
                    imagemPersonalizar.setImageURI(imagemUrl);
                } else if (codigoResultado == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
                    Exception erro = result.getError();
                }
            }
        } catch (NullPointerException npex) {
            //
        }
    }
}
